package gui;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextField;

import client.ClientConsole;

import logic.BorrowHistory;
import logic.Message;
import logic.Reader;

/**
 * Shows a reader window and reader's history.
 * allows to extend loan books, enables edit details.
 */
public class ReaderWindow extends JPanel implements ActionListener{
	/**  GUI Panels used for Design*/
	private JPanel mainPanel,topPanel,searchPanel,centerPanel,bottomPanel,searchTextPanel,radioPanel;
	private JTextField bookSearch,cellphone,email;
	/** button representing all reader's action options*/
	private JButton search;
	private JButton editDetails;
	private JButton logout;
	private JLabel hello,borrowedBookLabel,borrowDateLabel,returnDateLabel,actualReturnDateLabel,errorLabel,confirmationLabel;
	/** radio Button for search selection*/
	JRadioButtonMenuItem  bookName,bookAuthor,freeText,subject;
	/** holds message form server*/
	Message msg;
	/** holds reader's history*/
	Object[] o;
	/** saves the properties of the GridBagLayout for*/
	GridBagConstraints gbc = new GridBagConstraints();
	/** Container for radio buttons*/ 
	ButtonGroup bGroup = new ButtonGroup();
	
	/**Default constructor-reader window*/
	public ReaderWindow()
	{
		super();
		int i=1;
		int index=0;
		mainPanel=new JPanel();
		mainPanel.setLayout(new BorderLayout());
		bookSearch=new JTextField(20);
		search= new JButton("Search");
		search.addActionListener(this);
		topPanel=new JPanel();
		topPanel.setLayout(new BorderLayout());
		searchPanel=new JPanel();
		searchPanel.setLayout( new BoxLayout( searchPanel, BoxLayout.Y_AXIS ) );
		searchTextPanel=new JPanel();
		radioPanel= new JPanel();
		searchTextPanel.add(bookSearch);
		searchTextPanel.add(search);
		bookName=new JRadioButtonMenuItem ("Book name");
		subject=new JRadioButtonMenuItem ("Subject");
		bookAuthor=new JRadioButtonMenuItem ("Author");
		freeText=new JRadioButtonMenuItem ("Free Text");
		bGroup.add(bookName);
		bGroup.add(bookAuthor);
		bGroup.add(subject);
		bGroup.add(freeText);
		radioPanel.add(bookName);
		radioPanel.add(bookAuthor);
		bookName.setSelected(true);
		radioPanel.add(subject);
		radioPanel.add(freeText);
		searchPanel.add(searchTextPanel);
		searchPanel.add(radioPanel);
		hello=new JLabel("Hello "+ClientConsole.reader.getUsername()+",");
		topPanel.add(searchPanel,BorderLayout.CENTER);
		topPanel.add(hello,BorderLayout.WEST);
		mainPanel.add(topPanel,BorderLayout.NORTH);
		centerPanel=new JPanel();
		centerPanel.setLayout(new GridBagLayout());
		getOrders();
		//if has history
		if (msg.getCommand().equals("History Found"))
		{
			borrowedBookLabel=new JLabel("Book Name");
			gbc = new GridBagConstraints();
			gbc.gridx=0;
			gbc.gridy=0;
			gbc.insets= new Insets(7,7,7,7);
			centerPanel.add(borrowedBookLabel,gbc);
			borrowDateLabel=new JLabel("Borrow Date");
			gbc = new GridBagConstraints();
			gbc.gridx=1;
			gbc.gridy=0;
			gbc.insets= new Insets(7,7,7,7);
			centerPanel.add(borrowDateLabel,gbc);
			returnDateLabel=new JLabel("Return Date");
			gbc = new GridBagConstraints();
			gbc.gridx=2;
			gbc.gridy=0;
			gbc.insets= new Insets(7,7,7,7);
			centerPanel.add(returnDateLabel,gbc);
			actualReturnDateLabel=new JLabel("Actual return Date");
			gbc = new GridBagConstraints();
			gbc.gridx=3;
			gbc.gridy=0;
			gbc.insets= new Insets(7,7,7,7);
			centerPanel.add(actualReturnDateLabel,gbc);
			
			String pattern="yyyy-MM-dd";
			SimpleDateFormat dateFormat=new SimpleDateFormat(pattern);
			//show all borrow history
			for (index=0;index<o.length;index++)
			{
				JLabel borrowedBook=new JLabel(String.valueOf(((BorrowHistory) o[index]).getCatalogNumber()));
				gbc = new GridBagConstraints();
				gbc.gridx=0;
				gbc.gridy=i;
				gbc.insets= new Insets(4,4,4,4);
				centerPanel.add(borrowedBook,gbc);
				JLabel borrowDate=new JLabel(dateFormat.format(((BorrowHistory) o[index]).getBorrowDate()));
				gbc = new GridBagConstraints();
				gbc.gridx=1;
				gbc.gridy=i;
				gbc.insets= new Insets(4,4,4,4);
				centerPanel.add(borrowDate,gbc);
				JLabel returnDate=new JLabel(dateFormat.format(((BorrowHistory) o[index]).getReturnDate()));
				gbc = new GridBagConstraints();
				gbc.gridx=2;
				gbc.gridy=i;
				gbc.insets= new Insets(4,4,4,4);
				centerPanel.add(returnDate,gbc);
				
				if (((BorrowHistory) o[index]).getActualReturnDate()!=null)
				{
					JLabel  actualReturnDate = new JLabel(dateFormat.format(((BorrowHistory) o[index]).getActualReturnDate()));
					gbc = new GridBagConstraints();
					gbc.gridx=3;
					gbc.gridy=i++;
					gbc.insets= new Insets(4,4,4,4);
					centerPanel.add(actualReturnDate,gbc);
				}
				else
				{
					Calendar cal=Calendar.getInstance();
					long day1 = cal.getTimeInMillis(); // in milliseconds.
					long day2 = ((BorrowHistory) o[index]).getReturnDate().getTime(); // in milliseconds.
					long days = (day2 - day1) / 86400000;
					JLabel  actualReturnDate = new JLabel("");
					gbc = new GridBagConstraints();
					gbc.gridx=3;
					gbc.gridy=i;
					gbc.insets= new Insets(4,4,4,4);
					centerPanel.add(actualReturnDate,gbc);
					if (days<=7 && days>=0)
					{
						JButton  extendButton = new JButton("Extend Return");
						extendButton.setName(String.valueOf(index));
						gbc = new GridBagConstraints();
						gbc.gridx=4;
						gbc.gridy=i++;
						gbc.insets= new Insets(4,4,4,4);
						centerPanel.add(extendButton,gbc);
						extendButton.addActionListener(this);
					}
					else
						i++;
					
				}
			}
		}
		else
		{
			errorLabel=new JLabel();
			errorLabel.setText(msg.getCommand());
			centerPanel.add(errorLabel);
		}
		JLabel  actualReturnDate = new JLabel("");
		gbc = new GridBagConstraints();
		gbc.gridx=0;
		gbc.gridy=i++;
		gbc.gridwidth=4;
		gbc.insets= new Insets(20,20,20,20);
		centerPanel.add(actualReturnDate,gbc);
		JLabel  cellphoneLabel = new JLabel("Cellphone: ");
		gbc = new GridBagConstraints();
		gbc.gridx=0;
		gbc.gridy=i;
		gbc.gridwidth=2;
		gbc.insets= new Insets(4,4,4,4);
		centerPanel.add(cellphoneLabel,gbc);
		cellphone = new JTextField(15);
		gbc = new GridBagConstraints();
		gbc.gridx=2;
		gbc.gridy=i++;
		gbc.gridwidth=2;
		gbc.insets= new Insets(4,4,4,4);
		cellphone.setText(ClientConsole.reader.getCellphone());
		centerPanel.add(cellphone,gbc);
		JLabel  emailLabel = new JLabel("Email: ");
		gbc = new GridBagConstraints();
		gbc.gridx=0;
		gbc.gridy=i;
		gbc.gridwidth=2;
		gbc.insets= new Insets(4,4,4,4);
		centerPanel.add(emailLabel,gbc);
		email = new JTextField(15);
		gbc = new GridBagConstraints();
		gbc.gridx=2;
		gbc.gridy=i++;
		gbc.gridwidth=2;
		gbc.insets= new Insets(4,4,4,4);
		email.setText(ClientConsole.reader.getEmail());
		centerPanel.add(email,gbc);
		editDetails = new JButton("Edit Details");
		gbc = new GridBagConstraints();
		gbc.gridx=1;
		gbc.gridy=i++;
		gbc.gridwidth=2;
		gbc.insets= new Insets(4,4,4,4);
		centerPanel.add(editDetails,gbc);
		editDetails.addActionListener(this);
		confirmationLabel = new JLabel();
		gbc = new GridBagConstraints();
		gbc.gridx=0;
		gbc.gridy=i;
		gbc.gridwidth=4;
		gbc.insets= new Insets(4,4,4,4);
		confirmationLabel.setVisible(false);
		centerPanel.add(confirmationLabel,gbc);
		mainPanel.add(centerPanel,BorderLayout.CENTER);
		bottomPanel=new JPanel(new BorderLayout());
		logout=new JButton("Logout");
		logout.addActionListener(this);
		bottomPanel.add(logout,BorderLayout.WEST);
		mainPanel.add(bottomPanel,BorderLayout.SOUTH);
		add(mainPanel);
	}
	
	/** gets readers history*/
	private void getOrders() {
		msg=new Message ("Reader History",ClientConsole.reader);
		ClientConsole.HandleMessageFromGui(msg);
		msg=(Message)ClientConsole.client.getMessage();
		if (msg.getCommand().equals("History Found"))
			o=(Object[]) msg.getObjects();
		
	}
	//Handles user's clicks on buttons
	@Override
	public void actionPerformed(ActionEvent ae) {
		if (ae.getSource()==search)
		{
			if (!bookSearch.getText().isEmpty())
			{
				String query=bookSearch.getText();
				String option = "";
				
				if (bookName.isSelected())
					option="Book Name";
				else if (bookAuthor.isSelected())
					option="Author";
				else if (subject.isSelected())
					option="Subject";
				else if (freeText.isSelected())
					option="Free";
				this.setVisible(false);
				ClientConsole.aFrame.setContentPane(new SearchForm(query,option));
			}
		}
		else if (ae.getSource()==logout)
		{
			Message m;
			m=new Message("logout",ClientConsole.reader);
			ClientConsole.HandleMessageFromGui(m);	
			m=(Message)ClientConsole.client.getMessage();
			ClientConsole.reader=null;
			this.setVisible(false);
			ClientConsole.aFrame.setContentPane(new LoginForm());
		}
		else if (ae.getSource()==editDetails)
		{
			Reader r=new Reader(ClientConsole.reader);
			r.setEmail(email.getText());
			r.setCellphone(cellphone.getText());
			msg=new Message ("Reader Edit",r);
			ClientConsole.HandleMessageFromGui(msg);
			msg=(Message)ClientConsole.client.getMessage();
			if (msg.getCommand().equals("The Reader is edited"))
			{
				ClientConsole.reader=r;
				confirmationLabel.setVisible(true);
				confirmationLabel.setText("The reader edited successfully");
			}
		}
		else
		{
			String name;
			name=((JButton) ae.getSource()).getName();
			System.out.println(name);
			BorrowHistory borrow=(BorrowHistory) o[Integer.parseInt(name)];
			Reader r=new Reader(ClientConsole.reader);
			Object[] arr=new Object[2];
			arr[0]=borrow;
			arr[1]=r;
			Message msg=new Message ("ReaderExtend",arr);
			ClientConsole.HandleMessageFromGui(msg);
			msg=(Message)ClientConsole.client.getMessage();
			if (msg.getCommand().equals("Return date extended for 3 days"))
			{
				confirmationLabel.setVisible(true);
				confirmationLabel.setText(msg.getCommand());
				this.setVisible(false);
				ClientConsole.aFrame.setContentPane(new ReaderWindow());
			}
			else
			{
				confirmationLabel.setVisible(true);
				confirmationLabel.setText(msg.getCommand());
			}
		}
	}

	
}
